package tieba.web;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import tieba.entity.CmsUser;
import tieba.service.ICmsUserService;
import tieba.web.entity.Result;

@Controller
@RequestMapping("/cmsuser")
public class CmsUserController {

	@Resource
	private ICmsUserService cmsUserService;

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(CmsUser user, ModelMap map) {
		cmsUserService.save(user);
		map.addAttribute("result", new Result("注册成功！", "/index"));
		return "/result/success";
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register() {
		return "redirect:/index";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(CmsUser user, HttpServletResponse resp) {
		if (cmsUserService.login(user) != null) {
			Cookie userCookie = new Cookie("user", user.getUsername() + ":"
					+ user.getPassword());
			userCookie.setMaxAge(1000 * 60 * 24 * 30);
			userCookie.setPath("/");
			resp.addCookie(userCookie);
			return "redirect:/menu";
		}
		return "/index";
	}

	@RequestMapping(value = "/loginout", method = RequestMethod.GET)
	public String loginout(HttpServletResponse resp) {
		Cookie cookie = new Cookie("user", null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		resp.addCookie(cookie);
		return "redirect:/index";
	}

}
